package com.sport.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sport.apis.setting.ISettingClient;
import com.sport.common.redis.CacheService;
import com.sport.common.redis.RedisKey;
import com.sport.model.common.dtos.ResponseResult;
import com.sport.model.common.enums.AppHttpCodeEnum;
import com.sport.model.setting.pojos.SportPreInfo;
import com.sport.model.user.dtos.AccountUserDto;
import com.sport.model.user.pojos.AccountUser;
import com.sport.model.user.vos.AccountUserVo;
import com.sport.user.mapper.AccountMapper;
import com.sport.user.repository.UserRepository;

import com.sport.user.service.LoginService;
import com.sport.utils.common.AlgorithmUtils;
import com.sport.utils.common.AppJwtUtil;
import com.sport.utils.common.BaseUtils;
import com.sport.utils.common.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class LoginServiceImpl extends ServiceImpl<AccountMapper, AccountUser> implements LoginService {

    @Resource
    private UserRepository userRepository;

    @Resource
    private ISettingClient iSettingClient;

    @Resource
    private CacheService cacheService;

    @Override
    public ResponseResult login(AccountUserDto accountUserDto) {
        //1.参数校验
        AccountUser account = userRepository.getAccount(accountUserDto);
        if(account==null)
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);

        String productSecretByAlgorithm = AlgorithmUtils.productSecretByAlgorithm(
                accountUserDto.getSchoolPassword()+account.getUuidSalt(),
                AlgorithmUtils.Algorithm.MD5_Algorithm
        );

        if (!productSecretByAlgorithm.equals(account.getSchoolPassword()))
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);

        //验证通过，返回token
        String token = AppJwtUtil.getToken(account.getSchoolTenementId());

        //查询该用户是否正在进行的运动会
        SportPreInfo preInfo = BaseUtils.mapToObjectConverter((Map) iSettingClient.getPreInfo(account.getSchoolTenementId()).getData(), SportPreInfo.class);

        //异步存储，加快响应，后续可使用消息队列确保成功
        //TODO: 后续的优化扩展
        ThreadPoolUtils.putOperationToThread(()->{
            Map<String, Object> parameterMap = new HashMap<>();
            if(preInfo == null) {
                //没有创建运动会
                //未初识化,进行初识化
                ResponseResult responseResult = iSettingClient.initSportMeeting(account.getSchoolTenementId());
                Long sportId = Long.valueOf(String.valueOf(responseResult.getData()));
                parameterMap.put("sportId", sportId);
                parameterMap.put("sportStatus", 0);
            } else {
                parameterMap.put("sportId", preInfo.getSportId());
                parameterMap.put("sportStatus", preInfo.getSportStatus());
            }

            //存到redis中
            cacheService.setMap(RedisKey.USER_INFORMATION + account.getSchoolTenementId(), parameterMap);
        });

        //返回
        AccountUserVo accountUserVo = BaseUtils.copyProperties(account, AccountUserVo.class);
        return ResponseResult.okResult(accountUserVo.setToken(token));
    }
}
